package com.micro.school.h5.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.micro.school.h5.service.WeChatService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@Service("WeChatServiceImpl")
public class WeChatServiceImpl implements WeChatService {


    private static final String appId = "";


    private static final String secret = "";

    private static final String WECHAT_API_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public String getOpenId(String code) {
        Map<String, String> result = getOpenIdAndSessionKey(code);
        return result.get("openid");
    }



    /**
     * 通过微信code获取用户的openId和session_key
     *
     * @param code 微信登录凭证code
     * @return 包含openId和sessionKey的Map
     */
    public Map<String, String> getOpenIdAndSessionKey(String code) {
        // 构建请求参数
        String url = WECHAT_API_URL + "?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);

        // 解析响应
        JSONObject jsonObject = JSON.parseObject(response);

        Map<String, String> result = new HashMap<>();
        if (jsonObject.containsKey("openid")) {
            result.put("openid", jsonObject.getString("openid"));
            result.put("session_key", jsonObject.getString("session_key"));

            // 如果有错误码，也返回错误信息
            if (jsonObject.containsKey("errcode")) {
                result.put("errcode", jsonObject.getString("errcode"));
                result.put("errmsg", jsonObject.getString("errmsg"));
            }
        } else {
            // 请求失败，返回错误信息
            result.put("errcode", jsonObject.getString("errcode"));
            result.put("errmsg", jsonObject.getString("errmsg"));
        }

        return result;
    }
}
